﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using FastReport;
using FastReport.Export;
using FastReport.Export.Pdf;
using FastReport.Export.OoXML;
using FastReport.Preview;
using Tzx.Utilities;
using FastReport.Export.Image;

namespace Tzx.Tools.Payroll2Images.Exe.TableToReport
{
    /// <summary>
    /// 表格数据,报表模板,加载到报表组件
    /// </summary>
    public partial class UcTableToReport : UserControl
    {

        #region 构造

        /// <summary>
        /// 构造
        /// </summary>
        public UcTableToReport()
        {
            InitializeComponent();

            //初始化
            InitReportTemplateFiles();

            //创建报表对象
            m_report = new Report();
        }

        /// <summary>
        /// 本应用程序目录有几个frx文件
        /// </summary>
        private void InitReportTemplateFiles()
        {
            CbReportFiles.Items.Clear();
            CbReportFiles.Items.Add("选择报表模板");

            //
            string dir = string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory);
            string[] frx_ss = Directory.GetFiles(dir, "*.frx");
            int idx_default = -1;
            foreach (string s in frx_ss)
            {
                string file_name = Path.GetFileName(s);
                int idx = CbReportFiles.Items.Add(file_name);
                if (IsDefaultFile(file_name))
                {
                    idx_default = idx;
                }
            }

            //默认选中项
            if (idx_default > -1)
            {
                CbReportFiles.SelectedIndex = idx_default;
            }
        }

        /// <summary>
        /// 是否为默认报表文件
        /// </summary>
        private bool IsDefaultFile(string file_name)
        {
            if (string.IsNullOrEmpty(file_name))
            {
                return false;
            }

            string[] ss = TEXT_report_file_name.Split('*');
            if (ss.Length == 0)
            {
                return false;
            }

            //
            bool isOk = true;
            foreach (string s in ss)
            {
                bool exist = file_name.IndexOf(s) > -1;
                isOk = isOk && exist;//都有这些文字
            }
            return isOk;
        }

        #endregion

        #region public

        /// <summary>
        /// 传入数据,打开预览
        /// </summary>
        /// <param name="table">数据表</param>
        public void SetDataPreview(DataTable table)
        {
            m_data = table;

            Rp_Preview();
        }

        /// <summary>
        /// 数据
        /// </summary>
        private DataTable m_data;

        #endregion

        /// <summary>
        /// 
        /// </summary>
        private const string TEXT_report_file_name = "*消息*模板*";

        /// <summary>
        /// 报表
        /// </summary>
        private Report m_report;

        #region private 属性

        /// <summary>
        /// Message标题
        /// </summary>
        private string Title
        {
            get
            {
                return Parent.Text;
            }
        }

        /// <summary>
        /// 当前选择报表文件完整路径和名称
        /// </summary>
        private string GetFrxFileFullPathName()
        {
            string frx_filename = string.Format("{0}", (string)CbReportFiles.SelectedItem);
            if (frx_filename.Length == 0)
            {
                MessageBox.Show("没有选择报表模板", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return null;
            }
            string frx_fullpathname = Path.Combine(string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory), frx_filename);
            if (!File.Exists(frx_fullpathname))
            {
                MessageBox.Show("报表模板文件不存在", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return null;
            }

            //
            return frx_fullpathname;
        }

        #endregion

        #region privite 方法

        /// <summary>
        /// 1.预览
        /// </summary>
        private void Rp_Preview()
        {
            string frx_fullpathname = GetFrxFileFullPathName();
            if (string.IsNullOrEmpty(frx_fullpathname))
            {
                MessageBox.Show("报表模板文件不存在", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (m_data == null)
            {
                MessageBox.Show("没有数据", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // 创建报表对象
            //m_report = new Report();
            
            // 释放之前加载的报表对象和预览控件
            //m_report.Dispose();            
            //m_report.Preview.Clear();//previewControl.Clear();

            try
            {
                // 加载报表模板文件(可选)
                //string frx_file = Path.Combine(string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory), "template.frx");
                m_report.Load(frx_fullpathname);

                // 注册数据源
                m_report.RegisterData(m_data, "Data");

                // 将数据源与报表绑定
                //report.GetDataSource("Data").Enabled = true;            
                // 获取报表数据源
                var dataSource = m_report.GetDataSource("Data");
                dataSource.Enabled = true; //启用报表数据源
                m_report.SetParameterValue("Data", dataSource);// 绑定数据源和报表对象

                // 将报表预览控件添加到窗体中
                if (m_report.Preview == null)
                {
                    m_report.Preview = new PreviewControl();
                }
                //panelFull.Controls.Add(m_report.Preview);//控件
                //m_report.Preview.Parent = panelFull;//控件
                //m_report.Preview.Dock = DockStyle.Fill;
                ShowPreviewControl(m_report.Preview);

                // 加载报表数据并刷新预览
                m_report.Prepare();
                m_report.ShowPrepared();
            }
            catch(Exception ex)
            {
                LogFile.Instance().LogException(ex);

                string ex_msg = string.Format("{0}\n\n{1}", ex.GetType().FullName, ex.Message);
                MessageBox.Show(ex_msg, "加载报表模板预览时出错", MessageBoxButtons.OK,MessageBoxIcon.Error);
            }            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ctl"></param>
        private void ShowPreviewControl(PreviewControl ctl)
        {
            int count = panelFull.Controls.Count;
            for (int i = count - 1; i >= 0; i--)
            {
                panelFull.Controls.RemoveAt(i);
            }

            // 将报表预览控件添加到窗体中
            //m_report.Preview = new PreviewControl();
            panelFull.Controls.Add(ctl);//控件
            ctl.Parent = panelFull;//控件
            ctl.Dock = DockStyle.Fill;

            ctl.ToolbarVisible = false;
        }

        /// <summary>
        /// 2.导出
        /// </summary>
        private void Rp_Export()
        {
            // 导出报表
            using (var saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "PDF 文件|*.pdf|Excel 文件|*.xls|jpg图片文件|*.jpg";
                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                ExportBase export = null;
                if (saveFileDialog.FilterIndex == 1)
                {
                    export = new PDFExport();
                }
                else if (saveFileDialog.FilterIndex == 2)
                {
                    export = new Excel2007Export();
                }
                else if (saveFileDialog.FilterIndex == 3)
                {
                    //export = new ImageExport();
                    ImageExport exportImg = new ImageExport();
                    exportImg.ImageFormat = ImageExportFormat.Jpeg;
                    export = exportImg;
                }

                //
                if (export != null)
                {
                    m_report.Prepare();
                    m_report.Export(export, saveFileDialog.FileName);
                }

            }//using

            //
        }

        /// <summary>
        /// 3.设计
        /// </summary>
        private void Rp_Design()
        {
            //
            string frx_fullpathname = GetFrxFileFullPathName();
            if (string.IsNullOrEmpty(frx_fullpathname))
            {
                MessageBox.Show("报表模板文件不存在", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            //
            if (m_data == null)
            {
                MessageBox.Show("没有数据", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            try
            {

                // 创建报表对象
                //m_report = new Report();

                // 加载报表模板文件(可选)
                m_report.Load(frx_fullpathname);

                // 注册数据源
                m_report.RegisterData(m_data, "Data");

                // 将数据源与报表绑定
                m_report.GetDataSource("Data").Enabled = true;

                m_report.Design();

                // 设置报表设计器的父控件为当前窗体
                //report.Designer.Parent = panelFull;
                //report.Designer.Dock = DockStyle.Fill;

                // 显示报表设计器
                //report.Designer.Show();

                // 将报表预览控件添加到窗体中
                //report.Preview = new PreviewControl();
                //report.Preview.Parent = this;
                //report.Preview.Dock = DockStyle.Fill;

            }
            catch (Exception ex)
            {
                LogFile.Instance().LogException(ex);

                string ex_msg = string.Format("{0}\n\n{1}", ex.GetType().FullName, ex.Message);
                MessageBox.Show(ex_msg, "设计报表模板时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 按钮事件

        /// <summary>
        /// 预览
        /// </summary>        
        private void BtnPreview_Click(object sender, EventArgs e)
        {
            // 释放之前加载的报表对象和预览控件
            m_report.Preview.Clear();
            m_report.Preview.Dispose();
            m_report.Dispose();
            m_report = new Report();

            Rp_Preview();
        }

        /// <summary>
        /// 设计
        /// </summary>        
        private void BtnDesign_Click(object sender, EventArgs e)
        {
            Rp_Design();
        }

        /// <summary>
        /// 导出图片
        /// </summary>        
        private void BtnExport_Click(object sender, EventArgs e)
        {
            Rp_Export();
        }

        #endregion        


    }
}
